package org.example.protocol;

import org.smartboot.socket.Protocol;
import org.smartboot.socket.transport.AioSession;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * 字符串通信协议
 *
 * @author Tamako
 */
public class StringProtocol implements Protocol<String> {
    @Override
    public String decode(ByteBuffer byteBuffer, AioSession aioSession) {
        int remaining = byteBuffer.remaining();
        if (remaining < Integer.BYTES) {
            return null;
        }
        byteBuffer.mark();
        int length = byteBuffer.getInt();
        if (length > byteBuffer.remaining()) {
            byteBuffer.reset();
            return null;
        }
        byte[] b = new byte[length];
        byteBuffer.get(b);
        return new String(b, StandardCharsets.UTF_8);
    }
}